package com.zygh.coordinatestore.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zygh.coordinatestore.entity.Coordinate;
import com.zygh.coordinatestore.mapper.CoordinateMapper;
import com.zygh.coordinatestore.service.AsyncService;
import com.zygh.coordinatestore.service.CoordinateService;
import com.zygh.coordinatestore.util.RandomLonLat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AsyncServiceImpl implements AsyncService {
    private static Logger logger = LogManager.getLogger(AsyncServiceImpl.class.getName());
    @Autowired
    private CoordinateMapper coordinateMapper;
    @Autowired
    private CoordinateService coordinateService;

    @Async("asyncServiceExecutor")
    public void writeTxt() {
        logger.info("线程-" + Thread.currentThread().getId() + "在执行写入");
        try {
            System.out.println("线程" + Thread.currentThread().getId() + "开始执行");
            Coordinate coordinate = new Coordinate();
            for (int i = 1; i < 1000; i++) {
                coordinate.setLonLats("113.700193,34.763197;113.732703,34.764265;113.732735,34.765146;113.736759,34.766927");
                coordinateService.insertSelective(coordinate);
            }
            System.out.println("线程" + Thread.currentThread().getId() + "执行结束");
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }

    @Override
    public void writeupdate() {
        logger.info("线程-" + Thread.currentThread().getId() + "在执行写入");
        try {
            System.out.println("线程" + Thread.currentThread().getId() + "开始执行");
            //查询所有id
            List<Coordinate> allId = coordinateMapper.findAllId();
            for (int i = 0; i < allId.size(); i++) {
                Thread t = new Thread() {
                    public void run() {
                        try {
                            Coordinate coordinate = allId.get(RandomUtil.randomInt(0, 999));
                            coordinate.setId(coordinate.getId());
                            coordinate.setLonLats(RandomLonLat.randomGps());
                            coordinateService.updateByPrimaryKeySelective(coordinate);
                        } catch (Exception ie) {
                            ie.printStackTrace();
                        }
                    }
                };
                t.start();


            }
            System.out.println("线程" + Thread.currentThread().getId() + "执行结束");
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }

}
